package cn.edu.seu.ssny.controller.admin.system;

import cn.edu.seu.ssny.common.JsonResult;
import cn.edu.seu.ssny.controller.BaseController;
import cn.edu.seu.ssny.entity.*;
import cn.edu.seu.ssny.service.*;
import cn.edu.seu.ssny.service.specification.SimpleSpecificationBuilder;
import cn.edu.seu.ssny.service.specification.SpecificationOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/admin/device")
public class DeviceController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(DeviceController.class);


    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private IGatewayService gatewayService;
    @Autowired
    private IDeviceTemplateService deviceTemplateService;

    @RequestMapping(value = {"/", "/index/{id}"})
    public String index(@PathVariable Integer id, ModelMap map) {
        Project project = projectService.find(id);
        map.put("project", project);
        return "admin/device/index";
    }

    @RequestMapping(value = {"/list/{id}"})
    @ResponseBody
    public Page<Device> list(@PathVariable Integer id) {
        SimpleSpecificationBuilder<Device> builder = new SimpleSpecificationBuilder<Device>();
        builder.add("project", SpecificationOperator.Operator.eq.name(), projectService.find(id));
        Page<Device> page = deviceService.findAll(builder.generateSpecification(), getPageRequest());
        return page;
    }

    @RequestMapping(value = {"/listByEquipment/{id}"})
    @ResponseBody
    public Page<Device> listByEquipment(@PathVariable Integer id) {
        SimpleSpecificationBuilder<Device> builder = new SimpleSpecificationBuilder<Device>();
        builder.add("equipment", SpecificationOperator.Operator.eq.name(), equipmentService.find(id));
        Page<Device> page = deviceService.findAll(builder.generateSpecification(), getPageRequest());
        return page;
    }

    @RequestMapping(value = "/add/{id}", method = RequestMethod.GET)
    public String add(@PathVariable Integer id, ModelMap map) {
        //对应项目的
        map.put("project", projectService.find(id));
        map.put("gateways", gatewayService.findAll());
        map.put("templates", deviceTemplateService.findAll());
        return "admin/device/form";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable Integer id, ModelMap map) {
        Device device = deviceService.find(id);
        map.put("device", device);
        map.put("project", device.getProject());
        map.put("gateways", gatewayService.findAll());
        map.put("templates", deviceTemplateService.findAll());
        return "admin/device/form";
    }

    @RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult edit(Device device, ModelMap map, HttpSession session) {
        String gateway_id = request.getParameter("gateway_id");
        String project_id = request.getParameter("project_id");
        String template_id = request.getParameter("template_id");
        Project project = projectService.find(Integer.parseInt(project_id));
        Gateway gateway = gatewayService.find(Integer.parseInt(gateway_id));
        DeviceTemplate template = deviceTemplateService.find(Integer.parseInt(template_id));
        try {
            logger.info(device.toString());
            deviceService.saveOrUpdate(device, (Enterprise) session.getAttribute("enterprise"), project, gateway, template);
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delete(@PathVariable Integer id, ModelMap map) {
        try {
            deviceService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/deletems/{ids}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult deletems(@PathVariable String ids, ModelMap map) {
        if (ids == null)
            return JsonResult.failure("删除失败");
        String[] idArray = ids.split("&");
        for (String id : idArray) {
            try {
                deviceService.delete(Integer.parseInt(id));
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResult.failure(e.getMessage());
            }
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/display/{id}", method = RequestMethod.GET)
    public String display(@PathVariable Integer id, ModelMap map) {
        Device device = deviceService.find(id);
        Project project = device.getProject();
        List<Device> devices = deviceService.findByProject(project);
        map.put("currDevice", device);
        map.put("devices", devices);
        return "admin/device/display";
    }

    @RequestMapping(value = {"/display/edit"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult displayEdit(Device device, ModelMap map, HttpSession session) {
        try {
            System.out.println(device.getCoordinateX());
            deviceService.saveCoordinate(device);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

}
